package com.keter.framework.cloud;

import com.keter.framework.cloud.component.interceptor.GlobalInterceptor;
import com.keter.framework.cloud.component.interceptor.SIDInterceptor;
import com.keter.framework.web.component.http.HttpClienter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collections;

/**
 * Created by gulixing@msn.com on 2019/3/2.
 */
@ComponentScan("com.keter.framework.cloud.component")
@Component
public class AutoConfiguration {

    @Autowired
    HttpClienter httpClienter;

    @Autowired
    SIDInterceptor sidInterceptor;

    /**
     * 全局默认RestTemplate
     * @return
     */
    @Primary
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        // 使用OkHttp3构造restTemplate客户端
        RestTemplate restTemplate = httpClienter.restTemplate();
        // 添加SID拦截器
        restTemplate.setInterceptors(Collections.singletonList(sidInterceptor));
        return restTemplate;
    }

    public  RestTemplate restTemplate(int READ_TIMEOUT_SEC){
        RestTemplate restTemplate = httpClienter.restTemplate(READ_TIMEOUT_SEC);
        // 添加SID拦截器
        restTemplate.setInterceptors(Collections.singletonList(sidInterceptor));
        return restTemplate;
    }

    @Configuration
    static class WebAppConfigurer implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 可添加多个
            registry.addInterceptor(new GlobalInterceptor()).addPathPatterns("/**");
        }
    }
}
